package com.group4.Servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import com.google.gson.Gson;
import com.group4.DAO.VideoCommentDAO;
import com.group4.DAO.VideoDAO;
import com.group4.DB.Video;
import com.group4.DB.VideoComment;
import com.group4.Utility.SemanticallySimilarWordsFinder;
import com.group4.Utility.JSON.VideoToJson;
import com.group4.Utility.JSON.VideosToJson;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SearchServlet
 */
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stubs
		System.out.println("Searching...");
		String input = request.getParameter("srchterm");
		StringBuilder temp = new StringBuilder(input);
		for(int i = 0; i < temp.length(); i++){
			if(temp.charAt(i) == ' '){
				temp.setCharAt(i,'_');
			}
		}
		input = temp.toString();
		ArrayList<String> terms = new ArrayList<String>();
		terms.add(input);
		terms.addAll(SemanticallySimilarWordsFinder.findSimilarWords(input));	
		System.out.println(terms.toString());
		ArrayList<VideoDAO> videos = new ArrayList<VideoDAO>();
		ArrayList<VideoCommentDAO> comments = new ArrayList<VideoCommentDAO>();
		VideoToJson tempVideo;
		VideosToJson results = new VideosToJson();
		Gson gson = new Gson();
		
		for(int i = 0; i < terms.size(); i++){
			videos.addAll(Video.getVideosWithTag(terms.get(i)));
		}
		for(int i = 0; i < videos.size(); i++){
			comments = VideoComment.getAllVideosCommentsWithVideoID(videos.get(i).getID());
			tempVideo = new VideoToJson(videos.get(i),comments);
			results.videos.add(tempVideo);
		}
		
		String result = gson.toJson(results.videos);
		System.out.println(result);
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		out.print(result);
		out.flush();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
